/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.moneygrosService;

import java.lang.ref.WeakReference;

import android.app.DownloadManager.Request;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.example.moneygrosService.MainActivityService.DB_TOKEN;
import com.example.moneygrosService.MainActivityService.REQUEST_CODES;
import com.example.moneygrosService.database.MoneyContract.UserProfilesColumns;
import com.example.moneygrosService.database.MoneyContract.UsersColumns;

/**
 * Slightly more abstract {@link AsyncQueryHandler} that helps keep a
 * {@link WeakReference} back to a listener. Will properly close any
 * {@link Cursor} if the listener ceases to exist.
 * <p>
 * This pattern can be used to perform background queries without leaking
 * {@link Context} objects.
 *
 * @hide pending API council review
 */
public class MoneyServiceAsyncQueryHandler extends AsyncQueryHandler {
	private static final String TAG = "MoneyServiceAsyncQueryHandler";
    private DatabaseService mService;
    public MoneyServiceAsyncQueryHandler(ContentResolver resolver, DatabaseService service) {
        super(resolver);
        mService = service;
    }

//    /**
//     * Begin an asynchronous query with the given arguments. When finished,
//     * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is
//     * called if a valid {@link AsyncQueryListener} is present.
//     */
//    public void startQuery(Uri uri, String[] projection) {
//        startQuery(-1, null, uri, projection, null, null, null);
//    }
//
//    /**
//     * Begin an asynchronous query with the given arguments. When finished,
//     * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called
//     * if a valid {@link AsyncQueryListener} is present.
//     *
//     * @param token Unique identifier passed through to
//     *            {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)}
//     */
//    public void startQuery(int token, Uri uri, String[] projection) {
//        startQuery(token, null, uri, projection, null, null, null);
//    }
//
//    /**
//     * Begin an asynchronous query with the given arguments. When finished,
//     * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called
//     * if a valid {@link AsyncQueryListener} is present.
//     */
//    public void startQuery(Uri uri, String[] projection, String sortOrder) {
//        startQuery(-1, null, uri, projection, null, null, sortOrder);
//    }
//
//    /**
//     * Begin an asynchronous query with the given arguments. When finished,
//     * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called
//     * if a valid {@link AsyncQueryListener} is present.
//     */
//    public void startQuery(Uri uri, String[] projection, String selection,
//            String[] selectionArgs, String orderBy) {
//        super.startQuery(-1, null, uri, projection, selection, selectionArgs, orderBy);
//    }
//    /**
//     * Begin an asynchronous query with the given arguments. When finished,
//     * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called
//     * if a valid {@link AsyncQueryListener} is present.
//     */
//    public void startQuery(int token, Uri uri, String[] projection, String selection,
//            String[] selectionArgs, String orderBy) {
//        super.startQuery(token, null, uri, projection, selection, selectionArgs, orderBy);
//    }    
//    /**
//     * Begin an asynchronous query with the given arguments. When finished,
//     * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called
//     * if a valid {@link AsyncQueryListener} is present.
//     */
//    public void startQuery(int token, Object cookie, Uri uri, String[] projection, String selection,
//            String[] selectionArgs, String orderBy) {
//        super.startQuery(token, cookie, uri, projection, selection, selectionArgs, orderBy);
//    }
//
//    /**
//     * Begin an asynchronous update with the given arguments.
//     */
//    public void startUpdate(Uri uri, ContentValues values) {
//        startUpdate(-1, null, uri, values, null, null);
//    }    
//
//    public void startInsert(Uri uri, ContentValues values) {
//        startInsert(-1, null, uri, values);
//    }
//    public void startInsert(int token, Uri uri, ContentValues values) {
//        startInsert(token, null, uri, values);
//    }
//
//    public void startDelete(Uri uri) {
//        startDelete(-1, null, uri, null, null);
//    }

    /** {@inheritDoc} */
    @Override
    protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch(token){
//		case DB_TOKEN.INSERT_BALANCE:
//		case DB_TOKEN.CHECK_BALANCE:
//			Log.v(TAG, "CHECK_BALANCE");
//    		mAdapter.changeCursor(cursor);
//    		break;
//    		
//		case DB_TOKEN.CHECK_USER_FOR_INSERT:
//			Log.v(TAG, "CHECK_USER");
//			if(cursor != null){
//				if(cursor.getCount() == 0){
//					cursor.close();
//	    			Log.v(TAG, "inserting user");
//					insertUser((User)cookie);
//				} else {
//	    			Log.v(TAG, "existing user");
//	    			Toast.makeText(context, "existing user", Toast.LENGTH_SHORT).show();
//				}
//			}    				
//    		break;
//    		
//		case DB_TOKEN.CHECK_USER_FOR_BALANCE_UPDATE:
//			Log.v(TAG, "CHECK_USER_FOR_BALANCE_UPDATE");
//			if(cursor != null){
//				if(cursor.getCount() != 0){
//					cursor.moveToFirst();
//					Request request = (Request)cookie;
//					
//					request.setUser_id(cursor.getString(cursor.getColumnIndex(UsersColumns.USER_ID)));
//					request.setFormer_balance(cursor.getFloat(cursor.getColumnIndex(UsersColumns.BALANCE)));
//					request.setRespondant_user(cursor.getInt(cursor.getColumnIndex(UsersColumns.BIDIRECTIONAL))!=0);
//					
//					request.setNew_balance(request.getOffset() + request.getFormer_balance());
//					
//					cursor.close();
//	    			Log.v(TAG, "updating balance, new balance="+ request.getNew_balance());
//	    			if(request.isRespondant_user()){
//	    				// faire un requete communication
//	    				// ajouter dans la table des requetes 
//	    				sendRequest(request);
//	    				sendSMS("5554", request.getUser_id()+ request.getNew_balance());
////	    				sendSMS("0633287589", request.getUser_id()+ request.getNew_balance());
//	    			} else {
//	    				updateBalance(request.getUser_id(), request.getNew_balance());
//	    			}
//	    			
//	    			// faire requete de Pending ou Log
//				}
//			}
//				
//    		break;
		case DB_TOKEN.CHECK_USER_PROFILE_FOR_ACTIVITY:
			Log.v(TAG, "CHECK_USER_PROFILE_FOR_ACTIVITY");
			if(cursor != null){
				Bundle bundle = new Bundle();
				bundle.putInt("request_code", REQUEST_CODES.MODIFY_USER_PROFILE);
				if(cursor.getCount() != 0){
					//l'utilisateur existe!
					//update fields values
					cursor.moveToFirst();
					Log.v(TAG, "userprofile exists");

					User user = new User();
					
					user.setUser_id(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.USER_ID)));
					user.setUser_name(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.USER_NAME)));
					user.setPhone_number(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.PHONE_NUMBER)));
					user.setBluetooth_MAC(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.BLUETOOTH_MAC)));

					bundle.putParcelable("user", user);

					cursor.close();
				}
				mService.sendMsg(bundle);
			}
			break;
		case DB_TOKEN.CHECK_USER_UPDATE_USER_PROFILE:
			Log.v("TAGeryListener", "CHECK_USER_UPDATE_USER_PROFILE");
			if(cursor != null){
				User user = (User)cookie;
				if(cursor.getCount() != 0){
					//l'utilisateur existe!
					cursor.moveToFirst();

	    			Log.v(TAG, "update user profile");
					user.setVersion(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.VERSION)));

					mService.updateUserProfile(user);
					
				} else {
					//l'utilisateur n'existe pas!
					// l'insérer
					Log.v(TAG, "insert user profile");
					user.setVersion("1.0");
					mService.insertUserProfile(user);
	    			
				}

				cursor.close();
			}
				
    		break;
    		
		}
    }

	@Override
	protected void onDeleteComplete(int token, Object cookie, int result) {		
		//TODO 
	}
	@Override 
	protected void onInsertComplete(int token, Object cookie, Uri uri) {		
		//TODO
	}
    
	@Override
	protected void onUpdateComplete(int token, Object cookie, int result) {		
		//TODO 
	}
    
}
